/*================================================================
*   Copyright (C) 2020 belonging to YangZhengQing. All rights reserved.
*   
*   文件名称：named_socket_server.c
*   创 建 者：YangZhengQing
*   创建日期：2020年03月11日
*   描    述：
*
*================================================================*/


//#include "named_socket_server.h"


#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<errno.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<sys/un.h>

#define SOCKET_PATH "socket_path"//命名socket通信路径
#define LINK_NUMS 5//连接数
#define SIZE	50

int main(int argc, char **argv)
{
	int					sockfd		= -1;
	int					clientfd	= -1;
	struct sockaddr_un	server_addr;//服务器配置结构体
	struct sockaddr_un	client_addr;//缓存客户端信息结构体
	int					client_len;
	int					rv = -1;
	char				buff[SIZE];

	sockfd = socket(AF_UNIX, SOCK_STREAM, 0);//创建套接字，第三参数0会自动匹配与参数二适应的协议
	if(sockfd < 0)
	{
		printf("socket error:%s\n",strerror(errno));
		exit(0);
	}

	//判断socket文件是否存在
	if(!access(SOCKET_PATH, F_OK))
	{
		unlink(SOCKET_PATH);
	}

	//初始化服务器
	memset(&server_addr, 0, sizeof(server_addr));
	server_addr.sun_family = AF_UNIX;
	strncpy(server_addr.sun_path, SOCKET_PATH, sizeof(SOCKET_PATH)-1);//减一是因为去掉字符串中‘\0’

	if(bind(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)
	{
		printf("bind error:%s\n",strerror(errno));
		goto Cleanup;
	}

	listen(sockfd, LINK_NUMS);


	printf("Starting to wait client to link...\n");

	clientfd = accept(sockfd, (struct sockaddr *)&client_addr, &client_len);//开始等待连接
	if(clientfd < 0)
	{
		printf("accept error:%s\n",strerror(errno));
		goto Cleanup;
	}

	//读数据
	memset(buff, 0, sizeof(buff));
	rv = read(clientfd, buff, sizeof(buff));
	if(rv < 0)
	{
		printf("named_server read error:%s\n",strerror(errno));
		goto Cleanup;
	}
	else if(rv == 0)
	{
		printf("named_client disconnect!\n");
		goto Cleanup;
	}
	printf("named_server received [%d] bytes from named_client:%s\n",rv,buff);

	//回显
	rv = write(clientfd, "named_server received over!", 28);
	if(rv < 0)
	{
		printf("named_server write error:%s\n",strerror(errno));
		goto Cleanup;
	}


Cleanup:
	close(sockfd);
	close(clientfd);
	unlink(SOCKET_PATH);
	exit(0);



}
